package com.xktpx.controller;

import com.xktpx.common.utils.R;
import com.xktpx.config.WxChatConfig;
import com.xktpx.entity.model.PayOrder;
import com.xktpx.service.AlipaymentOrderService;
import com.xktpx.service.WxPostDataInfoService;
import com.xktpx.utils.wx.IdUtils;
import com.xktpx.utils.wx.PayCommonUtil;
import com.xktpx.utils.wx.PayConfigUtil;
import com.xktpx.utils.wx.WxUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author 杨浩
 * @create 2018-12-30 14:59
 **/
@RestController
@RequestMapping("/api/pay")
@Api(tags = "支付")
public class ApiPayController {

    Logger logger = LoggerFactory.getLogger(ApiPayController.class);

    @Autowired
    protected AlipaymentOrderService alipaymentOrderService;

    @Autowired
    protected WxPostDataInfoService wxPostDataInfoService;


    /**
     * 点击“立即购买”时调用，同时生成订单数据
     *
     * */
    @ApiOperation("取微信支付最终调用参数")
    @PostMapping("/getWeixinPayParams")
    @ResponseBody
    public Map<String, Object> getWxPayParams(
            @ApiParam("订单id") @RequestParam("orderId") Integer orderId,
            @ApiParam("用户id") @RequestParam("userid") String userid,
            @ApiParam("微信openid") @RequestParam("openid") String openid,
            @ApiParam("订单金额") @RequestParam("money") String money) {
        logger.info("获取微信支付最终调用参数");
        Map<String, Object> configMap = new HashMap<>();

        try {

            Map<String, String> payMap = PayCommonUtil.wxUnifiedorder(orderId, money, userid, "APP", openid);
            logger.info("payMap--->" + payMap);

            String prepayId = Objects.toString(payMap.get("prepay_id"), "");
            long time = System.currentTimeMillis() / 1000;
            String appid = PayConfigUtil.APP_ID;
            String key = PayConfigUtil.API_KEY; // key
            String packageStr = "prepay_id=" + prepayId;
            String nonceStr = PayCommonUtil.getRandomString(32);
            SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
            packageParams.put("appId", appid);
            packageParams.put("nonceStr", nonceStr);
            packageParams.put("package", packageStr);
            packageParams.put("signType", "MD5");
            packageParams.put("timeStamp", time + "");

            String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);

            configMap.put("appId", appid);
            configMap.put("timeStamp", time + "");
            configMap.put("nonceStr", nonceStr);
            configMap.put("signType", "MD5");
            configMap.put("paySign", sign);
            configMap.put("package", packageStr);
            logger.info("支付参数---->" + configMap);
        } catch (Exception e) {
            e.printStackTrace();
            configMap.put("result", "fail");
            return configMap;
        }

        return configMap;
    }

    /**
     * 支付完成后的异步回调接口
     *
     * */
    @ApiOperation("微信支付回调接口")
    @PostMapping("/weixinPayNotify")
    @ResponseBody
    public String weixinPayNotify(HttpServletRequest request) {

        // 微信回调回来的是xml格式的文档。
        // 通过parseXml直接将request请求转换成xml再转换成map，然后就可以键值对取值了
        Map<String, String> map = new HashMap<>();
        try {
            map = WxUtil.parseXml(request);
        } catch (Exception e) {
            logger.info("解析xml文档异常", e);
            map = null;
        }

        return wxPostDataInfoService.nofify(map);

    }

    /**
     * 点击“立即购买”时调用，同时生成订单数据
     *
     * */
    @ApiOperation("获取支付宝加签后的订单信息字符串")
    @PostMapping("/getAliPayOrderStr")
    public String getAliPayOrderStr(
            @ApiParam("订单id") @RequestParam("orderId") Integer orderId,
            @ApiParam("商品金额") @RequestParam("amount") String amount,
            @ApiParam("商品名称") @RequestParam("proName") String proName,
            @ApiParam("商品描述") @RequestParam("proDesc") String proDesc) {
        // 获取回调参数
        PayOrder payOrder = new PayOrder();
        // 订单贸易号
        String outTradeNo = IdUtils.uuid();
        payOrder.setBody(proDesc);
        payOrder.setOutTradeNo(outTradeNo);
        payOrder.setId(orderId);
        payOrder.setSubjecy(proName);
        payOrder.setTotalAmount(amount);
        return alipaymentOrderService.getAliPayOrderStr(payOrder);
    }

    /**
     * 支付完成后的异步回调接口
     *
     * */
    @ApiOperation("支付宝支付回调接口")
    @PostMapping("/aliPayNotify")
    @ResponseBody
    public String aliPayNotify(HttpServletRequest request) {

        // 获取回调参数
        //获取支付宝返回的参数集合
        Map<String, String[]> aliParams = request.getParameterMap();
        //用以存放转化后的参数集合
        Map<String, String> conversionParams = new HashMap<String, String>();
        for (Iterator<String> iter = aliParams.keySet().iterator(); iter.hasNext();) {
            String key = iter.next();
            String[] values = aliParams.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "uft-8");
            conversionParams.put(key, valueStr);
        }
        logger.info("==================返回参数集合："+conversionParams);
        return alipaymentOrderService.notify(conversionParams);
    }

}
